package tjs.styudy.mini.springboot.devtools.fileWatch;


import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class FileListenerAdaptor extends FileAlterationListenerAdaptor {

    private static final Logger logger = LoggerFactory.getLogger(FileListenerAdaptor.class);

    private ApplicationEventPublisher eventPublisher;
    private List<File> changeFiles;

    public FileListenerAdaptor(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }

    public FileListenerAdaptor() {
    }

    @Override
    public void onStart(FileAlterationObserver arg0) {
        //System.out.println("begin listening!");
        this.changeFiles = new ArrayList<>();
    }

    @Override
    public void onStop(FileAlterationObserver arg0) {
        //System.out.println("end listening!");
        if (!CollectionUtils.isEmpty(this.changeFiles)) {
            logger.info("存在{}个文件变更，开始发布变更事件。。。", this.changeFiles.size());
            Set<Object> changeSet = this.changeFiles.stream().map(File::getPath).collect(Collectors.toSet());
            eventPublisher.publishEvent(new ClassPathChangedEvent(changeSet, true));
           try {
               Thread.currentThread().sleep(2000);
           }catch (InterruptedException ex){
               ex.printStackTrace();
           }
        }
    }

    @Override
    public void onDirectoryCreate(File fold) {
        System.out.println("fold: " + fold.getAbsolutePath() + " is created.");
    }

    @Override
    public void onDirectoryChange(File fold) {
        System.out.println("fold: " + fold.getAbsolutePath() + " is changed.");
    }

    @Override
    public void onDirectoryDelete(File fold) {
        System.out.println("fold: " + fold.getAbsolutePath() + " is deleted.");
    }

    @Override
    public void onFileCreate(File file) {
        System.out.println("file: " + file.getAbsolutePath() + " is created.");
        this.changeFiles.add(file);
    }

    @Override
    public void onFileChange(File file) {
        System.out.println("file: " + file.getAbsolutePath() + " is changed.");
        this.changeFiles.add(file);
    }

    @Override
    public void onFileDelete(File file) {
        System.out.println("file: " + file.getAbsolutePath() + " is deleted");
        this.changeFiles.add(file);
    }

}